package com.longlong.utils;


/*
* token工具类
* 生成token，用户登录拿到token然后访问资源
* */

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {

    @Value("${jwt.secret}")
    private String secret;


    @Value("${jwt.expiration}")
    private long expiration;


    /*
    * 传入用户登录信息
    *
    * */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> map = new HashMap<>();
        map.put("username",userDetails.getUsername());
        map.put("created",new Date());
        return this.getSecretJwt(map);
    }

    /*
     * 生成token
     * */
    private String getSecretJwt(Map<String, Object> map){
        return Jwts.builder()
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS512, secret)
                .setExpiration(new Date(System.currentTimeMillis()+expiration*1000))
                .compact();
    }

    /*
    * 根据token获取荷载信息
    * */
    public Claims getTokenBody(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }


    /*
    * 根据token获取用户信息
    * */
    public String getUsernameByToken(String token){
        Claims tokenBody = this.getTokenBody(token);
        System.out.println("tokenBody=================================="+tokenBody);
        if(null == tokenBody){
            return null;
        }
        return (String) tokenBody.get("username");
    }

    public String isCorrect(String token){
        return this.getTokenBody(token).getIssuer();
    }

    /*
    * 验证token是否过期
    * */
    public boolean isException(String token){
        return this.getTokenBody(token).getExpiration().before(new Date());
    }


    /*
    * token刷新
    * */
    public String RefreshToken(String token){
        Claims claims = this.getTokenBody(token);
        claims.setExpiration(new Date());
        return getSecretJwt(claims);
    }



}










